package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.ExcelSubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

public class SubjectExcelListener extends AnalysisEventListener<ExcelSubjectData> {

    //因为SubjectExcelListener不能交给spring管理 需要自己new  所以在SubjectExcelListener中不能注入其他组件
    //手动注入service
    public EduSubjectService eduSubjectService;

    public SubjectExcelListener() { }

    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }
    //读取excel内容 一行一行进行读取
    @Override
    public void invoke(ExcelSubjectData excelSubjectData, AnalysisContext analysisContext) {
        if(excelSubjectData == null){
            throw new GuliException(20001,"文件内容为空");
        }
        //一行一行读取 每行读取两个值 第一个值是一级分类 第二个值是二级分类
        EduSubject oneSubject = this.existOneSubject(eduSubjectService, excelSubjectData.getOneSubjectName());
        if(oneSubject==null){//表中不存在
            oneSubject = new EduSubject();
            oneSubject.setTitle(excelSubjectData.getOneSubjectName());
            oneSubject.setParentId("0");
            eduSubjectService.save(oneSubject);
        }
        String pid = oneSubject.getId();//一级分类的id 就是二级分类的pid
        EduSubject twoSubject = this.existTwoSubject(eduSubjectService, excelSubjectData.getTwoSubjectName(), pid);
        if(twoSubject == null){//二级分类不重复
            twoSubject= new EduSubject();
            twoSubject.setParentId(pid);
            twoSubject.setTitle(excelSubjectData.getTwoSubjectName());
            eduSubjectService.save(twoSubject);


        }

    }
    //分类不能重复  判断一级分类是否存在
    public EduSubject existOneSubject(EduSubjectService eduSubjectService,String name){
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title",name);
        queryWrapper.eq("parent_id","0");
        EduSubject oneSubject = eduSubjectService.getOne(queryWrapper);
        return  oneSubject;
    }
    //判断二级分类是否存在
    public EduSubject existTwoSubject(EduSubjectService eduSubjectService,String  name,String pid){
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title",name);
        queryWrapper.eq("parent_id",pid);
        EduSubject twoSubject = eduSubjectService.getOne(queryWrapper);
        return  twoSubject;
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
